import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:ytbusiness/config/yt_theme.dart';
import 'package:ytbusiness/utils/screen_adaptation.dart';
import 'package:ytbusiness/widgets/widgets.dart';
import 'package:ytbusiness/utils/helper.dart';
import 'package:ytbusiness/routes.dart';

/// 扫码登录
///
/// 调用qr_code_scanner库扫码 根据结果跳转到结果页面，或者提示结果
class Scanner extends StatefulWidget {
  @override
  _ScannerState createState() => _ScannerState();
}

class _ScannerState extends State<Scanner> {
  Barcode result;
  QRViewController controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  // In order to get hot reload to work we need to pause the camera
  // if the platform is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: customAppBar(context, title: "扫码登录PC"),
      body: Container(
        child: _buildQrView(context),
      ),
    );
  }

  ///创建扫码view
  ///
  ///在预览画面上添加 扫码区域
  Widget _buildQrView(BuildContext context) {
    var scanArea = setWidth(250);
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification
    // and update controller
    return NotificationListener<SizeChangedLayoutNotification>(
        onNotification: (notification) {
          Future.microtask(
              () => controller?.updateDimensions(qrKey, scanArea: scanArea));
          return false;
        },
        child: SizeChangedLayoutNotifier(
            key: const Key('qr-size-notifier'),
            child: Container(
              child: QRView(
                key: qrKey,
                onQRViewCreated: _onQRViewCreated,
                overlay: QrScannerOverlayShape(
                    borderColor: YTTheme.theme,
                    borderRadius: 10,
                    borderLength: 30,
                    borderWidth: 10,
                    cutOutSize: scanArea,
                    cutOutBottomOffset: setWidth(60)),
              ),
            )));
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      print("扫码结果---->${scanData.format}");

      print("扫码结果---->${scanData.code}");
      Navigator.pop(context);
      urlPush(
          context,
          RouteManager.route(RouteManager.scannerResult) +
              "?scanner_txt=${scanData.code}");
      controller.dispose();
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
